<template>
  <div>
    <el-form :inline="true" :model="searchAgain" ref="ruleFormRef" :rules="rules">
      <div>
        <el-popover v-model:visible="upCard" trigger="click" :width="400">
          <template #reference>
            <el-form-item class="again" prop="upCity" @click="upCard = !upCard">
              <el-input v-model="searchAgain.upCity" placeholder="出发城市" maxlength="10" size="large"
                @blur="upCard = false" :prefix-icon="LocalTwo" />
            </el-form-item>
          </template>

          <div class="card">
            <el-card class="box-card">
              <template #header>
                <div class="card-header">
                  <span>出发城市</span>
                </div>
              </template>

              <div v-for="item in city" class="text" :key="item.index">
                <div @mousedown="upCityChoice(item, -1)">{{ item }}</div>
              </div>
            </el-card>
          </div>
        </el-popover>

        <el-form-item>
          <p @click="exchange(-1)" class="exchange">
            <Switch theme="outline" size="26" fill="#333" />
          </p>
        </el-form-item>
        <el-popover v-model:visible="downCard" trigger="click" :width="400">
          <template #reference>
            <el-form-item class="again" prop="downCity" @click="downCard = !downCard">
              <el-input v-model="searchAgain.downCity" placeholder="到达城市" maxlength="10" size="large"
                @blur="downCard = false" :prefix-icon="LocalTwo" />

            </el-form-item>
          </template>
          <div class="downCard">
            <el-card class="box-card">
              <template #header>
                <div class="card-header">
                  <span style="font-size: 16px;">终点城市</span>
                </div>
              </template>
              <div v-for="item in city" class="text" :key="item.index">
                <div @mousedown="downCityChoice(item, -1)">
                  {{ item }}
                </div>
              </div>
            </el-card>
          </div>

        </el-popover>


        <el-form-item class="again" prop="upDate" :rules="[
          {
            validator: validateRoundendTime,
            trigger: 'blur'
          },
        ]">
          <el-col :span="11">
            <el-date-picker v-model="searchAgain.upDate" format="YYYY/MM/DD" value-format="YYYY-MM-DD" type="date"
              placeholder="选择日期" size="large" style="width: 220px" :disabled-date="disabled" @change="isAll()" />
          </el-col>
        </el-form-item>
        <el-form-item class="again" :prop="porps.radio === 2 ? 'downDate' : '1'" v-if="radio == 2">
          <el-col :span="11" v-if="show">
            <el-date-picker v-model="searchAgain.downDate" format="YYYY/MM/DD" value-format="YYYY-MM-DD" type="date"
              placeholder="选择日期" size="large" style="width: 220px" :disabled-date="returnDisabled" @change="isAll()" />
          </el-col>
        </el-form-item>
        <el-form-item v-if="radio != 3">
          <el-button class="again_button" type="warning" plain @click="again_onSubmit">重新搜索</el-button>
        </el-form-item>
      </div>
      <div v-if="radio == 3">
        <div v-for="(data, index) in searchAgain.domains " :key="index">
          <el-popover v-model:visible="data.upCard_state" trigger="click" :width="400">
            <template #reference>
              <el-form-item class="again" :prop="'domains.' + index + '.upCity'" @click="inheritanceCity(index)" :rules="[
                {
                  required: true,
                  message: '出发地城市不能为空',
                  trigger: 'blur',
                }
              ]">
                <el-input v-model="data.upCity" placeholder="出发城市" maxlength="10" size="large"
                  @blur="data.upCard_state = false" :prefix-icon="LocalTwo" />
              </el-form-item>
            </template>

            <div class="card">
              <el-card class="box-card">
                <template #header>
                  <div class="card-header">
                    <span>出发城市</span>
                  </div>
                </template>
                <div v-for="item in city" class="text" :key="item.index">
                  <div @mousedown="upCityChoice(item, index)">{{ item }}</div>
                </div>
              </el-card>
            </div>
          </el-popover>
          <el-form-item>
            <p @click="exchange(index)" class="exchange">
              <Switch theme="outline" size="26" fill="#333" />
            </p>
          </el-form-item>
          <el-popover v-model:visible="data.downCard_state" trigger="click" :width="400">
            <template #reference>
              <el-form-item class="again" :prop="'domains.' + index + '.downCity'"
                @click="data.downCard_state = !data.downCard_state" :rules="[
                  {
                    required: true,
                    message: '目的地城市不能为空',
                    trigger: 'blur',
                  }
                ]">
                <el-input v-model="data.downCity" placeholder="到达城市" maxlength="10" size="large"
                  @blur="data.downCard_state = false" :prefix-icon="LocalTwo" />
              </el-form-item>
            </template>
            <div class="downCard">
              <el-card class="box-card">
                <template #header>
                  <div class="card-header">
                    <span style="font-size: 16px;">终点城市</span>
                  </div>
                </template>
                <div v-for="item in city" class="text" :key="item.index">
                  <div @mousedown="downCityChoice(item, index)">
                    {{ item }}
                  </div>
                </div>
              </el-card>
            </div>
          </el-popover>
          <el-form-item class="again" :prop="'domains.' + index + '.upDate'" :rules="[
            {
              required: true,
              message: '出发日期不能为空',
              trigger: 'blur'
            },
            {
              validator: validateendTime,
              trigger: 'blur'
            }
          ]">
            <el-col :span="11">
              <el-date-picker v-model="data.upDate" format="YYYY/MM/DD" value-format="YYYY-MM-DD" type="date"
                placeholder="选择日期" size="large" style="width: 220px" :disabled-date="multipassDisabled[index]"
                @change="isAll()" />
            </el-col>
          </el-form-item>
          <el-button class="close_one" @click="removeDomain(index)" v-if="index + 1 != searchAgain.domains.length">
            <close-one theme="outline" size="24" fill="#979797" />
          </el-button>
          <el-form-item v-if="index + 1 == searchAgain.domains.length">
            <el-button class="again_button" type="warning" plain @click="again_onSubmit">重新搜索</el-button>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <el-button type="warning" plain v-if="radio === 3 && layerNumber < 4" @click="layerNumber++">再加一程+</el-button>
  </div>
</template>
<script setup>
import { ref, reactive, getCurrentInstance, watch, computed, defineProps } from "vue";
import { Switch, CloseOne, LocalTwo } from "@icon-park/vue-next"
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import url from "../../common/js/APIUtil";
import { defineEmits } from 'vue'
import { useStore } from '../../store/store';

//路由
const router = useRouter();
const route = useRoute();
// 调用函数 获得Store
const store = useStore();

const layerNumber = ref(1)


const porps = defineProps({
  radio: {
    type: Number,
    default: 1
  },
})

//启航时间限制
var disabled = (time) => {
  return time.getTime() < Date.now() - 8.64e7;
};
//返程时间限制
let returnDisabled = computed(() => {
  return (time) => {
    if (searchAgain.upDate != '' && searchAgain.upDate != null) {
      return time.getTime() < new Date(Date.parse(searchAgain.upDate.replace(/-/g, "/")) + 8.64e7);
    } else {
      return time.getTime() < Date.now() - 8.64e7;
    }
  };
})
//多程时间限制
var multipassDisabled = reactive(['', '', '', ''])

//返回日期
const show = ref(true)

const { proxy } = getCurrentInstance();
//绑定父组件事件
const emit = defineEmits(['again_onSubmit'])
//表单数据
var upCard = ref(false);
var downCard = ref(false);
const searchAgain = reactive({
  upCity: route.query.upCity,
  downCity: route.query.downCity,
  upDate: route.query.upDate,
  downDate: route.query.downDate,
  domains: [{ upCity: '', downCity: '', upDate: '', upCard_state: false, downCard_state: false },]
});

//监视搜索数据而改变日期限制
watch(() => searchAgain.domains, () => {
  multipassDisabled[0] = (time) => {
    if (searchAgain.upDate != '' && searchAgain.upDate != null) {
      return time.getTime() < new Date(Date.parse(searchAgain.upDate.replace(/-/g, "/")) + 8.64e7);
    } else {
      return time.getTime() < Date.now() - 8.64e7;
    }
  };
  for (let i = 1; i < searchAgain.domains.length; i++) {
    multipassDisabled[i] = (time) => {
      let date = ''
      for (let j = i; j > 0; j--) {
        if (searchAgain.domains[j - 1].upDate != '' && searchAgain.domains[j - 1].upDate != null) {
          date = searchAgain.domains[j - 1].upDate
          break;
        }
      }
      if (date == '' && searchAgain.upDate != '' && searchAgain.upDate != null) {
        date = searchAgain.upDate
      } else if (date == '') {
        return time.getTime() < Date.now() - 8.64e7;
      }
      return time.getTime() < new Date(Date.parse(date.replace(/-/g, "/")) + 8.64e7);
    }
  }
}, { deep: true })

//往返日与多层日期验证
let validateRoundendTime = (rule, value, callback,) => {
  if (porps.radio === 2) {
    if (new Date(searchAgain.downDate).getTime() <= new Date(value).getTime()) {
      if (searchAgain.downDate) {
        callback(new Error('启程日期不能晚于或等于返程日期'))
      }
    } else {
      callback()
    }
  } else if (porps.radio == 3) {
    let have = false
    for (let index = 0; index < searchAgain.domains.length; index++) {
      if (searchAgain.domains[index].upDate) {
        if (new Date(searchAgain.domains[index].upDate).getTime() <= new Date(value).getTime()) {
          have = true
        }
      }
    }

    if (have) {
      callback(new Error('先程日期不能晚于或等于后程日期'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

//多程日期验证
let validateendTime = (rule, value, callback,) => {
  let have = false
  let num = -1
  for (let index = 0; index < searchAgain.domains.length; index++) {
    if (searchAgain.domains[index].upDate == value) {
      num = index + 1
      break
    }
  }
  for (let index = num; index < searchAgain.domains.length; index++) {
    if (new Date(searchAgain.domains[index].upDate).getTime() <= new Date(value).getTime()) {
      have = true
    }
  }
  if (new Date(searchAgain.upDate).getTime() == new Date(value).getTime()) {
    have = true
  }

  if (have) {
    callback(new Error('先程日期不能晚于或等于后程日期'))
  } else {
    callback()
  }
}

watch(layerNumber, (newValue, oldValue) => {
  if (newValue > oldValue) {
    searchAgain.domains.push({
      upCity: '',
      downCity: '',
      upDate: '',
      upCard_state: false,
      downCard_state: false
    })
  }
})

watch(route, (newValue, oldValue) => {

  //判断路径是否是航班搜索
  if (route.path.indexOf('/index/flightdynamic') >= 0) {
    show.value = false
    disabled = (time) => {
      return time.getTime() < Date.now() - 8.64e7 - (1 * 1000 * 60 * 60 * 24 * 3);
    };
  } else if (route.path.indexOf('/index/ticketinformation/multipass') >= 0) {
    searchAgain.domains = [{ upCity: '', downCity: '', upDate: '', upCard_state: false, downCard_state: false }]
    //刷新页面将多程数据写入到框
    let upCitys = route.query.upCity.split('_')
    let downCitys = route.query.downCity.split('_')
    let upDates = route.query.upDate.split('_')
    searchAgain.upCity = upCitys[0]
    searchAgain.downCity = downCitys[0]
    searchAgain.upDate = upDates[0]
    searchAgain.domains[0].upCity = upCitys[1]
    searchAgain.domains[0].downCity = downCitys[1]
    searchAgain.domains[0].upDate = upDates[1]
    for (let index = 2; index < upCitys.length; index++) {
      searchAgain.domains.push({
        upCity: upCitys[index],
        downCity: downCitys[index],
        upDate: upDates[index],
        upCard_state: false,
        downCard_state: false
      })
    }
  } else {
    searchAgain.domains = [{ upCity: '', downCity: '', upDate: '', upCard_state: false, downCard_state: false }]
  }
}, { immediate: true })


//表单验证
const ruleFormRef = ref();
const rules = reactive({
  upCity: [{ required: true, message: "出发城市不能为空", trigger: "blur" }],
  downCity: [
    { required: true, message: "目的地城市不能为空", trigger: "blur" },
  ],
  upDate: [{ required: true, message: "出发日期不能为空", trigger: "blur" }],
  downDate: [{ required: true, message: "返回日期不能为空", trigger: "blur" }],
});
watch(() => store.searchTypes, (newValue, oldValue) => {
  if (store.searchTypes !== 2) {
    ruleFormRef.value.clearValidate()
  }
})

const city = ref([]);

//城市交换
const exchange_data = ref();

const exchange = (index) => {
  if (index + 1) {
    exchange_data.value = searchAgain.domains[index].upCity
    searchAgain.domains[index].upCity = searchAgain.domains[index].downCity
    searchAgain.domains[index].downCity = exchange_data.value
  } else {
    exchange_data.value = searchAgain.upCity;
    searchAgain.upCity = searchAgain.downCity;
    searchAgain.downCity = exchange_data.value;
  }
  isAll()
};

const getCityAll = () => {
  proxy.$http.get(url.API_GET_citAll).then((res) => {
    city.value = Array.from(new Set(res.data.map(value => value.name)))
  });
};

const upCityChoice = (value, index) => {
  if (index + 1) {
    searchAgain.domains[index].upCard_state = false
    searchAgain.domains[index].upCity = value
  } else {
    searchAgain.upCity = value;
    upCard.value = false;
  }
  isAll()
};

const downCityChoice = (value, index) => {
  if (index + 1) {
    searchAgain.domains[index].downCard_state = false
    searchAgain.domains[index].downCity = value
  } else {
    searchAgain.downCity = value;
    downCard.value = false;
  }
  isAll()
};
//判断数据是否输入完成
var isAll = () => {
  let all = true
  for (const key in searchAgain) {
    let choose = key != 'domains'
    if (porps.radio == 1) {
      choose = key != 'domains' && key != 'downDate'
    }
    if (choose) {
      if (!searchAgain[key]) {
        all = false
        return
      }
    }
  }
  if (porps.radio == 3) {
    for (let index = 0; index < searchAgain.domains.length; index++) {
      for (const key in searchAgain.domains[index]) {
        if (key != 'upCard_state' && key != 'downCard_state') {
          if (!searchAgain.domains[index][key]) {
            all = false
            return
          }
        }
      }
    }
  }
  again_onSubmit()
}
//继承上一个终点城市
const inheritanceCity = (index) => {
  searchAgain.domains[index].upCard_state = !searchAgain.domains.upCard_state
  if (!searchAgain.domains[index].upCity && index > 0) {
    searchAgain.domains[index].upCity = searchAgain.domains[index - 1].downCity
  } else if (!searchAgain.domains[index].upCity) {
    searchAgain.domains[index].upCity = searchAgain.downCity
  }
  isAll()
}

// 删除一程
const removeDomain = (index) => {
  searchAgain.domains.splice(index, 1)
  layerNumber.value--
}

const again_onSubmit = () => {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      if (porps.radio === 2) {
        emit('again_onSubmit', searchAgain)
      } else if (porps.radio === 3) {
        let writeData = {
          upCity: searchAgain.upCity,
          downCity: searchAgain.downCity,
          upDate: searchAgain.upDate
        }
        searchAgain.domains.forEach(value => {
          writeData.upCity += '_' + value.upCity
          writeData.downCity += '_' + value.downCity
          writeData.upDate += '_' + value.upDate
        })
        emit('again_onSubmit', writeData)
      } else {
        emit('again_onSubmit', searchAgain)  // 之前子组件修改父组件的数据时需要添加'update:editConfirm'，但是触发父组件的方法不能加'update'
      }
    } else {
      ElMessage.error("请输入正确数据");
      return false;
    }
  })
}


getCityAll()
</script>

<style scoped land="less">
.card {
  width: 400px;

}

.card-header {
  height: 5px;
  transform: translate(0%, -140%);
}

.text {
  float: left;
  font-size: 15px;
  margin-right: 20px;
  margin-bottom: 20px;
  cursor: pointer;
}

.exchange {
  cursor: pointer;
  /* border: 1px solid rgba(0, 0, 0, 0.3); */
  border-radius: 20px;
}

.downCard {
  width: 400px;
  top: 60px;
}

.again_button {
  height: 40px;
  width: 180px;
}

.close_one {
  border: none;
  margin-bottom: 40px;
  transform: translate(0%, 60%);
  background-color: rgba(0, 0, 0, 0.0);
}

:deep(.el-form-item--small) {
  margin-bottom: 4px;
}
</style>